package com.example.common;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.example.admin_api.EmployeeClient;
import com.example.admin_model.dto.EmployeeDTO;
import com.example.config.JwtConfig;
import com.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 元数据对象处理器
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Resource
    private HttpServletRequest request;

    @Resource
    private EmployeeClient employeeClient;

    /**
     * 插入操作时,填入公共字段
     *
     * @param metaObject MetaObject 对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("公共字段自动填充[insert]...");
        String Id = this.getId();
        log.info("id:{}", Id);
        Date now = new Date();
        this.strictInsertFill(metaObject, "createTime", Date.class, now);
        this.strictInsertFill(metaObject, "updateTime", Date.class, now);
        this.strictInsertFill(metaObject, "createUser", String.class, Id);
        this.strictInsertFill(metaObject, "updateUser", String.class, Id);
    }

    /**
     * 更新操作时,公共字段填充
     *
     * @param metaObject MetaObject 对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("公共字段自动填充[update]...");
        String Id = this.getId();
        log.info("id:{}", Id);
        Date now = new Date();
        this.strictUpdateFill(metaObject, "updateTime", Date.class, now);
        this.strictUpdateFill(metaObject, "updateUser", String.class, Id);
    }

    public String getId() {
        //获取请求头中的token
        String token = request.getHeader("Authorization").replace("\"", "");
        log.info("token:{}", token);
        //new一个DTO对象,将token赋给DTO
        EmployeeDTO dto = new EmployeeDTO();
        dto.setToken(token);
        //验证token有效性,返回一个id
        String id = employeeClient.validate(dto);
        return id;
    }
}

